{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 11.11 \u8fdb\u7a0b\u95f4\u4f20\u9012Socket\u6587\u4ef6\u63cf\u8ff0\u7b26\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### \u95ee\u9898\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\u4f60\u6709\u591a\u4e2aPython\u89e3\u91ca\u5668\u8fdb\u7a0b\u5728\u540c\u65f6\u8fd0\u884c\uff0c\u4f60\u60f3\u5c06\u67d0\u4e2a\u6253\u5f00\u7684\u6587\u4ef6\u63cf\u8ff0\u7b26\u4ece\u4e00\u4e2a\u89e3\u91ca\u5668\u4f20\u9012\u7ed9\u53e6\u5916\u4e00\u4e2a\u3002\n\u6bd4\u5982\uff0c\u5047\u8bbe\u6709\u4e2a\u670d\u52a1\u5668\u8fdb\u7a0b\u76f8\u5e94\u8fde\u63a5\u8bf7\u6c42\uff0c\u4f46\u662f\u5b9e\u9645\u7684\u76f8\u5e94\u903b\u8f91\u662f\u5728\u53e6\u4e00\u4e2a\u89e3\u91ca\u5668\u4e2d\u6267\u884c\u7684\u3002"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### \u89e3\u51b3\u65b9\u6848\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\u4e3a\u4e86\u5728\u591a\u4e2a\u8fdb\u7a0b\u4e2d\u4f20\u9012\u6587\u4ef6\u63cf\u8ff0\u7b26\uff0c\u4f60\u9996\u5148\u9700\u8981\u5c06\u5b83\u4eec\u8fde\u63a5\u5230\u4e00\u8d77\u3002\u5728Unix\u673a\u5668\u4e0a\uff0c\u4f60\u53ef\u80fd\u9700\u8981\u4f7f\u7528Unix\u57df\u5957\u63a5\u5b57\uff0c\n\u800c\u5728windows\u4e0a\u9762\u4f60\u9700\u8981\u4f7f\u7528\u547d\u540d\u7ba1\u9053\u3002\u4e0d\u8fc7\u4f60\u65e0\u9700\u771f\u7684\u9700\u8981\u53bb\u64cd\u4f5c\u8fd9\u4e9b\u5e95\u5c42\uff0c\n\u901a\u5e38\u4f7f\u7528 multiprocessing \u6a21\u5757\u6765\u521b\u5efa\u8fd9\u6837\u7684\u8fde\u63a5\u4f1a\u66f4\u5bb9\u6613\u4e00\u4e9b\u3002"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\u4e00\u65e6\u4e00\u4e2a\u8fde\u63a5\u88ab\u521b\u5efa\uff0c\u4f60\u53ef\u4ee5\u4f7f\u7528 multiprocessing.reduction \u4e2d\u7684\nsend_handle() \u548c recv_handle() \u51fd\u6570\u5728\u4e0d\u540c\u7684\u5904\u7406\u5668\u76f4\u63a5\u4f20\u9012\u6587\u4ef6\u63cf\u8ff0\u7b26\u3002\n\u4e0b\u9762\u7684\u4f8b\u5b50\u6f14\u793a\u4e86\u6700\u57fa\u672c\u7684\u7528\u6cd5\uff1a"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "import multiprocessing\nfrom multiprocessing.reduction import recv_handle, send_handle\nimport socket\n\ndef worker(in_p, out_p):\n    out_p.close()\n    while True:\n        fd = recv_handle(in_p)\n        print('CHILD: GOT FD', fd)\n        with socket.socket(socket.AF_INET, socket.SOCK_STREAM, fileno=fd) as s:\n            while True:\n                msg = s.recv(1024)\n                if not msg:\n                    break\n                print('CHILD: RECV {!r}'.format(msg))\n                s.send(msg)\n\ndef server(address, in_p, out_p, worker_pid):\n    in_p.close()\n    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)\n    s.bind(address)\n    s.listen(1)\n    while True:\n        client, addr = s.accept()\n        print('SERVER: Got connection from', addr)\n        send_handle(out_p, client.fileno(), worker_pid)\n        client.close()\n\nif __name__ == '__main__':\n    c1, c2 = multiprocessing.Pipe()\n    worker_p = multiprocessing.Process(target=worker, args=(c1,c2))\n    worker_p.start()\n\n    server_p = multiprocessing.Process(target=server,\n                  args=(('', 15000), c1, c2, worker_p.pid))\n    server_p.start()\n\n    c1.close()\n    c2.close()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\u5728\u8fd9\u4e2a\u4f8b\u5b50\u4e2d\uff0c\u4e24\u4e2a\u8fdb\u7a0b\u88ab\u521b\u5efa\u5e76\u901a\u8fc7\u4e00\u4e2a multiprocessing \u7ba1\u9053\u8fde\u63a5\u8d77\u6765\u3002\n\u670d\u52a1\u5668\u8fdb\u7a0b\u6253\u5f00\u4e00\u4e2asocket\u5e76\u7b49\u5f85\u5ba2\u6237\u7aef\u8fde\u63a5\u8bf7\u6c42\u3002\n\u5de5\u4f5c\u8fdb\u7a0b\u4ec5\u4ec5\u4f7f\u7528 recv_handle() \u5728\u7ba1\u9053\u4e0a\u9762\u7b49\u5f85\u63a5\u6536\u4e00\u4e2a\u6587\u4ef6\u63cf\u8ff0\u7b26\u3002\n\u5f53\u670d\u52a1\u5668\u63a5\u6536\u5230\u4e00\u4e2a\u8fde\u63a5\uff0c\u5b83\u5c06\u4ea7\u751f\u7684socket\u6587\u4ef6\u63cf\u8ff0\u7b26\u901a\u8fc7 send_handle() \u4f20\u9012\u7ed9\u5de5\u4f5c\u8fdb\u7a0b\u3002\n\u5de5\u4f5c\u8fdb\u7a0b\u63a5\u6536\u5230socket\u540e\u5411\u5ba2\u6237\u7aef\u56de\u5e94\u6570\u636e\uff0c\u7136\u540e\u6b64\u6b21\u8fde\u63a5\u5173\u95ed\u3002"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\u5982\u679c\u4f60\u4f7f\u7528Telnet\u6216\u7c7b\u4f3c\u5de5\u5177\u8fde\u63a5\u5230\u670d\u52a1\u5668\uff0c\u4e0b\u9762\u662f\u4e00\u4e2a\u6f14\u793a\u4f8b\u5b50\uff1a"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\u6b64\u4f8b\u6700\u91cd\u8981\u7684\u90e8\u5206\u662f\u670d\u52a1\u5668\u63a5\u6536\u5230\u7684\u5ba2\u6237\u7aefsocket\u5b9e\u9645\u4e0a\u88ab\u53e6\u5916\u4e00\u4e2a\u4e0d\u540c\u7684\u8fdb\u7a0b\u5904\u7406\u3002\n\u670d\u52a1\u5668\u4ec5\u4ec5\u53ea\u662f\u5c06\u5176\u8f6c\u624b\u5e76\u5173\u95ed\u6b64\u8fde\u63a5\uff0c\u7136\u540e\u7b49\u5f85\u4e0b\u4e00\u4e2a\u8fde\u63a5\u3002"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### \u8ba8\u8bba\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\u5bf9\u4e8e\u5927\u90e8\u5206\u7a0b\u5e8f\u5458\u6765\u8bb2\u5728\u4e0d\u540c\u8fdb\u7a0b\u4e4b\u95f4\u4f20\u9012\u6587\u4ef6\u63cf\u8ff0\u7b26\u597d\u50cf\u6ca1\u4ec0\u4e48\u5fc5\u8981\u3002\n\u4f46\u662f\uff0c\u6709\u65f6\u5019\u5b83\u662f\u6784\u5efa\u4e00\u4e2a\u53ef\u6269\u5c55\u7cfb\u7edf\u7684\u5f88\u6709\u7528\u7684\u5de5\u5177\u3002\u4f8b\u5982\uff0c\u5728\u4e00\u4e2a\u591a\u6838\u673a\u5668\u4e0a\u9762\uff0c\n\u4f60\u53ef\u4ee5\u6709\u591a\u4e2aPython\u89e3\u91ca\u5668\u5b9e\u4f8b\uff0c\u5c06\u6587\u4ef6\u63cf\u8ff0\u7b26\u4f20\u9012\u7ed9\u5176\u5b83\u89e3\u91ca\u5668\u6765\u5b9e\u73b0\u8d1f\u8f7d\u5747\u8861\u3002"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "send_handle() \u548c recv_handle() \u51fd\u6570\u53ea\u80fd\u591f\u7528\u4e8e multiprocessing \u8fde\u63a5\u3002\n\u4f7f\u7528\u5b83\u4eec\u6765\u4ee3\u66ff\u7ba1\u9053\u7684\u4f7f\u7528\uff08\u53c2\u800311.7\u8282\uff09\uff0c\u53ea\u8981\u4f60\u4f7f\u7528\u7684\u662fUnix\u57df\u5957\u63a5\u5b57\u6216Windows\u7ba1\u9053\u3002\n\u4f8b\u5982\uff0c\u4f60\u53ef\u4ee5\u8ba9\u670d\u52a1\u5668\u548c\u5de5\u4f5c\u8005\u5404\u81ea\u4ee5\u5355\u72ec\u7684\u7a0b\u5e8f\u6765\u542f\u52a8\u3002\u4e0b\u9762\u662f\u670d\u52a1\u5668\u7684\u5b9e\u73b0\u4f8b\u5b50\uff1a"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# servermp.py\nfrom multiprocessing.connection import Listener\nfrom multiprocessing.reduction import send_handle\nimport socket\n\ndef server(work_address, port):\n    # Wait for the worker to connect\n    work_serv = Listener(work_address, authkey=b'peekaboo')\n    worker = work_serv.accept()\n    worker_pid = worker.recv()\n\n    # Now run a TCP/IP server and send clients to worker\n    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)\n    s.bind(('', port))\n    s.listen(1)\n    while True:\n        client, addr = s.accept()\n        print('SERVER: Got connection from', addr)\n\n        send_handle(worker, client.fileno(), worker_pid)\n        client.close()\n\nif __name__ == '__main__':\n    import sys\n    if len(sys.argv) != 3:\n        print('Usage: server.py server_address port', file=sys.stderr)\n        raise SystemExit(1)\n\n    server(sys.argv[1], int(sys.argv[2]))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\u8fd0\u884c\u8fd9\u4e2a\u670d\u52a1\u5668\uff0c\u53ea\u9700\u8981\u6267\u884c python3 servermp.py /tmp/servconn 15000 \uff0c\u4e0b\u9762\u662f\u76f8\u5e94\u7684\u5de5\u4f5c\u8005\u4ee3\u7801\uff1a"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# workermp.py\n\nfrom multiprocessing.connection import Client\nfrom multiprocessing.reduction import recv_handle\nimport os\nfrom socket import socket, AF_INET, SOCK_STREAM\n\ndef worker(server_address):\n    serv = Client(server_address, authkey=b'peekaboo')\n    serv.send(os.getpid())\n    while True:\n        fd = recv_handle(serv)\n        print('WORKER: GOT FD', fd)\n        with socket(AF_INET, SOCK_STREAM, fileno=fd) as client:\n            while True:\n                msg = client.recv(1024)\n                if not msg:\n                    break\n                print('WORKER: RECV {!r}'.format(msg))\n                client.send(msg)\n\nif __name__ == '__main__':\n    import sys\n    if len(sys.argv) != 2:\n        print('Usage: worker.py server_address', file=sys.stderr)\n        raise SystemExit(1)\n\n    worker(sys.argv[1])"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\u8981\u8fd0\u884c\u5de5\u4f5c\u8005\uff0c\u6267\u884c\u6267\u884c\u547d\u4ee4 python3 workermp.py /tmp/servconn .\n\u6548\u679c\u8ddf\u4f7f\u7528Pipe()\u4f8b\u5b50\u662f\u5b8c\u5168\u4e00\u6837\u7684\u3002\n\u6587\u4ef6\u63cf\u8ff0\u7b26\u7684\u4f20\u9012\u4f1a\u6d89\u53ca\u5230UNIX\u57df\u5957\u63a5\u5b57\u7684\u521b\u5efa\u548c\u5957\u63a5\u5b57\u7684 sendmsg() \u65b9\u6cd5\u3002\n\u4e0d\u8fc7\u8fd9\u79cd\u6280\u672f\u5e76\u4e0d\u5e38\u89c1\uff0c\u4e0b\u9762\u662f\u4f7f\u7528\u5957\u63a5\u5b57\u6765\u4f20\u9012\u63cf\u8ff0\u7b26\u7684\u53e6\u5916\u4e00\u79cd\u5b9e\u73b0\uff1a"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# server.py\nimport socket\n\nimport struct\n\ndef send_fd(sock, fd):\n    '''\n    Send a single file descriptor.\n    '''\n    sock.sendmsg([b'x'],\n                 [(socket.SOL_SOCKET, socket.SCM_RIGHTS, struct.pack('i', fd))])\n    ack = sock.recv(2)\n    assert ack == b'OK'\n\ndef server(work_address, port):\n    # Wait for the worker to connect\n    work_serv = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\n    work_serv.bind(work_address)\n    work_serv.listen(1)\n    worker, addr = work_serv.accept()\n\n    # Now run a TCP/IP server and send clients to worker\n    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)\n    s.bind(('',port))\n    s.listen(1)\n    while True:\n        client, addr = s.accept()\n        print('SERVER: Got connection from', addr)\n        send_fd(worker, client.fileno())\n        client.close()\n\nif __name__ == '__main__':\n    import sys\n    if len(sys.argv) != 3:\n        print('Usage: server.py server_address port', file=sys.stderr)\n        raise SystemExit(1)\n\n    server(sys.argv[1], int(sys.argv[2]))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\u4e0b\u9762\u662f\u4f7f\u7528\u5957\u63a5\u5b57\u7684\u5de5\u4f5c\u8005\u5b9e\u73b0\uff1a"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# worker.py\nimport socket\nimport struct\n\ndef recv_fd(sock):\n    '''\n    Receive a single file descriptor\n    '''\n    msg, ancdata, flags, addr = sock.recvmsg(1,\n                                     socket.CMSG_LEN(struct.calcsize('i')))\n\n    cmsg_level, cmsg_type, cmsg_data = ancdata[0]\n    assert cmsg_level == socket.SOL_SOCKET and cmsg_type == socket.SCM_RIGHTS\n    sock.sendall(b'OK')\n\n    return struct.unpack('i', cmsg_data)[0]\n\ndef worker(server_address):\n    serv = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\n    serv.connect(server_address)\n    while True:\n        fd = recv_fd(serv)\n        print('WORKER: GOT FD', fd)\n        with socket.socket(socket.AF_INET, socket.SOCK_STREAM, fileno=fd) as client:\n            while True:\n                msg = client.recv(1024)\n                if not msg:\n                    break\n                print('WORKER: RECV {!r}'.format(msg))\n                client.send(msg)\n\nif __name__ == '__main__':\n    import sys\n    if len(sys.argv) != 2:\n        print('Usage: worker.py server_address', file=sys.stderr)\n        raise SystemExit(1)\n\n    worker(sys.argv[1])"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\u5982\u679c\u4f60\u60f3\u5728\u4f60\u7684\u7a0b\u5e8f\u4e2d\u4f20\u9012\u6587\u4ef6\u63cf\u8ff0\u7b26\uff0c\u5efa\u8bae\u4f60\u53c2\u9605\u5176\u4ed6\u4e00\u4e9b\u66f4\u52a0\u9ad8\u7ea7\u7684\u6587\u6863\uff0c\n\u6bd4\u5982 Unix Network Programming by W. Richard Stevens\u00a0 (Prentice\u00a0 Hall,\u00a0 1990) .\n\u5728Windows\u4e0a\u4f20\u9012\u6587\u4ef6\u63cf\u8ff0\u7b26\u8ddfUnix\u662f\u4e0d\u4e00\u6837\u7684\uff0c\u5efa\u8bae\u4f60\u7814\u7a76\u4e0b multiprocessing.reduction \u4e2d\u7684\u6e90\u4ee3\u7801\u770b\u770b\u5176\u5de5\u4f5c\u539f\u7406\u3002"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.7.1"
    },
    "toc": {
      "base_numbering": 1,
      "nav_menu": {},
      "number_sections": true,
      "sideBar": true,
      "skip_h1_title": true,
      "title_cell": "Table of Contents",
      "title_sidebar": "Contents",
      "toc_cell": false,
      "toc_position": {},
      "toc_section_display": true,
      "toc_window_display": true
    }
  },
  "nbformat": 4,
  "nbformat_minor": 2
}